package com.xju.subjectsystem.utils;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * -*- coding:utf-8 -*-
 *
 * @projectName: Subjectsystem
 * @package: com.xju.subjectsystem.utils
 * @className: Md5Util
 * @author: Eiard
 * @description: DONE : MD5加密工具类
 * @date: 2024-12-04 11:48
 */
public class Md5Util {

    /**
     * @methodName: encrypt
     * @package: com.xju.subjectsystem.utils
     * @description: DONE : MD5加密
     * @author: Eiard
     * @date: 2024-12-06 18:02
     * @param: input    输入字符串
     * @return: String  返回加密后的MD5值（32位大写字母的十六进制表示）
     * @throws NoSuchAlgorithmException 如果未找到MD5算法
     */
    public static String encrypt(String input) throws NoSuchAlgorithmException {
        MessageDigest md = MessageDigest.getInstance("MD5");

        byte[] messageBytes = input.getBytes();
        byte[] digestBytes = md.digest(messageBytes);

        StringBuilder sb = new StringBuilder();
        for (byte b : digestBytes) {
            sb.append(String.format("%02x", b & 0xff));
        }

        return sb.toString();
    }

    /**
     * @methodName: verify
     * @package: com.xju.subjectsystem.utils
     * @description: DONE : 校验MD5值
     * @author: Eiard
     * @date: 2024-12-06 18:03
     * @param: input    输入字符串
     * @param: md5      需要比对的MD5值
     * @return: boolean 如果匹配返回true，否则返回false
     */
    public static boolean verify(String input, String md5) throws NoSuchAlgorithmException {
        String encrypted = encrypt(input);

        return encrypted.equals(md5);
    }

}
